<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-alert
        title="注意：只能选择三级商品分类！"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>

      <!-- 下拉选择框选择商品分类 -->
      <el-row class="cat-opts">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectedKey"
            :options="cateList"
            :props="cascaderProp"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- 标签页显示 -->
      <el-tabs v-model="activeName" @tab-click="handleTabsClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="small"
            :disabled="isBtnDisabled"
            @click="showDialog"
            >添加参数</el-button
          >
          <!-- 参数表格 -->
          <el-table :data="manyTableData" border>
            <!-- 展开项 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(tag, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  type="warning"
                  @close="removeParamsVal(scope.row, index)"
                >
                  {{ tag }}
                </el-tag>
                <!-- 动态编辑标签 -->
                <el-input
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                  class="input-new-tag"
                >
                </el-input>
                <el-button
                  v-else
                  size="small"
                  @click="showInput(scope.row)"
                  class="button-new-tag"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="small"
            :disabled="isBtnDisabled"
            @click="showDialog"
            >添加属性</el-button
          >
          <el-table :data="onlyTableData" border>
            <!-- 展开项 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(tag, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  type="warning"
                  @close="removeParamsVal(scope.row, index)"
                >
                  {{ tag }}
                </el-tag>
                <!-- 动态编辑标签 -->
                <el-input
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                  class="input-new-tag"
                >
                </el-input>
                <el-button
                  v-else
                  size="small"
                  @click="showInput(scope.row)"
                  class="button-new-tag"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="属性值" prop="attr_vals"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加动态参数/静态属性对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @closed="addDialogClosed"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="80px"
      >
        <el-form-item :label="titleText" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑动态参数/静态属性对话框 -->
    <el-dialog
      :title="'编辑' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @closed="editDialogClosed"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="120px"
      >
        <el-form-item :label="titleText + '名称'" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
        <el-form-item :label="titleText + '值'" prop="attr_vals">
          <el-input v-model="editForm.attr_vals"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      /* 级联选择框选择的商品分类id */
      selectedKey: [],
      cascaderProp: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
      },
      /* 标签页选中标签 */
      activeName: 'many',
      /* 动态参数数据 */
      manyTableData: [],
      /* 静态属性数据 */
      onlyTableData: [],
      /* 控制添加对话框的显示与隐藏 */
      addDialogVisible: false,
      /* 添加参数/属性对话框表单数据 */
      addForm: {
        name: '',
      },
      /* 添加对话框表单验证规则对象 */
      addFormRules: {
        name: [
          {
            required: true,
            message: '请输入动态参数（静态属性）名称!',
            trigger: 'blur',
          },
        ],
      },
      /* 控制编辑对话框的显示与隐藏 */
      editDialogVisible: false,
      editForm: {
        attr_id: '',
        attr_sel: '',
        attr_name: '',
        attr_vals: '',
      },
      editFormRules: {
        attr_name: [
          {
            required: true,
            message: '请输入动态参数（静态属性）名称',
            trigger: 'blur',
          },
        ],
        attr_vals: [
          {
            required: true,
            message: '请输入动态参数（静态属性）名称',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败！')
      }
      this.cateList = res.data
    },
    handleChange() {
      this.getParams()
    },
    handleTabsClick() {
      this.getParams()
    },
    /* 获取动态参数或静态属性 */
    async getParams() {
      if (this.selectedKey.length !== 3) {
        this.selectedKey = []
        return
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(`获取${this.titleText}失败！`)
      }
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    /* 显示添加动态参数/静态属性对话框 */
    showDialog() {
      this.addDialogVisible = true
    },
    /* 确认按钮添加参数/属性 */
    async addParams() {
      const { data: res } = await this.$http.post(
        `categories/${this.cateId}/attributes`,
        {
          attr_name: this.addForm.name,
          attr_sel: this.activeName,
        }
      )
      if (res.meta.status !== 201) {
        console.log(res)
        return this.$message.error(`添加${this.titleText}失败！`)
      }
      this.$message.success(`添加${this.titleText}成功！`)
      this.addDialogVisible = false
      this.getParams()
    },
    /* 添加对话框关闭时清空表单数据 */
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    /* 删除动态参数/静态属性 */
    deleteParams(param) {
      console.log(param)
      this.$confirm(`此操作将永久删除该${this.titleText}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.cateId}/attributes/${param.attr_id}`
          )
          if (res.meta.status !== 200) {
            this.$message.error(`该${this.titleText}删除失败！`)
          }
          this.$message.success(`该${this.titleText}删除成功！`)
          this.getParams()
        })
        .catch(() => {
          this.$message.info(`取消删除该${this.titleText}！`)
        })
    },
    /* 显示编辑动态参数/静态属性对话框 */
    showEditDialog(param) {
      this.editForm.attr_id = param.attr_id
      this.editForm.attr_sel = param.attr_sel
      this.editForm.attr_name = param.attr_name
      this.editForm.attr_vals = param.attr_vals
      this.editDialogVisible = true
    },
    /* 按钮确认修改参数信息 */
    editParams() {
      this.$refs.editFormRef.validate(async (value) => {
        if (!value) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.editForm.attr_sel,
            attr_vals: this.editForm.attr_vals,
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error(`${this.titleText}修改失败！`)
        }
        this.$message.success(`${this.titleText}修改成功！`)
        this.editDialogVisible = false
        this.getParams()
      })
    },
    /* 监听编辑对话框的关闭（清空表单数据） */
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    /* 动态添加标签输入框失去焦点 */
    async handleInputConfirm(row) {
      /* 标签输入框输入不合法数据 */
      if (row.inputValue.trim() === '') {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      /* 标签输入框输入合法数据 */
      row.attr_vals.push(row.inputValue)
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('添加' + this.titleText + '失败！')
      }
      row.inputValue = ''
      row.inputVisible = false
    },
    /* 点击添加标签按钮，显示输入框 */
    showInput(row) {
      row.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.focus()
      })
    },
    /* 删除对应动态参数/静态属性值 */
    async removeParamsVal(row, index) {
      row.attr_vals.splice(index, 1)
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(`删除${this.titleText}值失败！`)
      }
    },
  },

  computed: {
    isBtnDisabled() {
      if (this.selectedKey.length !== 3) {
        return true
      } else {
        return false
      }
    },
    cateId() {
      if (this.selectedKey.length === 3) {
        return this.selectedKey[2]
      }
      return null
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    },
  },
}
</script>

<style lang="less" scoped>
.cat-opts {
  margin: 15px 0;
}
.el-tag {
  margin: 5px 10px;
}
.input-new-tag {
  width: 120px;
  margin: 5px 10px;
}
.button-new-tag {
  margin: 5px 10px;
}
</style>